package com.electric.qrapp.utils.function

import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.electric.qrapp.R
import com.electric.qrapp.entity.bean.ApkUpDateBean
import com.electric.qrapp.net.HttpApi
import com.electric.qrapp.net.rxhttp.ErrorUtils
import com.pokemon.apkupdate.config.UpdateConfiguration
import com.pokemon.apkupdate.manager.DownloadManager
import rxhttp.awaitResult
import rxhttp.toOkResponse
import rxhttp.wrapper.param.RxHttp
import javax.inject.Inject


/**
 *@author created by WA03675
 *@date  2021-09-23 11:08
 *@des 更新Apk
 */
class ApkUpDateUtils @Inject constructor() : LifecycleEventObserver {


    private var manager: DownloadManager? = null

    suspend fun checkVersion( context: Context) {
        RxHttp.get(HttpApi.app_version)
            .toOkResponse()
            .awaitResult{


            }.onFailure {
                ErrorUtils.getError(it)
            }

//        if (BuildConfig.DEBUG) {
//            val bean = ApkUpDateBean(1, "v1.0.0", "有新版本需要更新哦 \n有新版本需要更新哦", "", true)
//            isNeedUpDate(bean, context)
//        }
    }

    private fun isNeedUpDate(apkUpDateBean: ApkUpDateBean, context: Context) {
        manager = manager ?: DownloadManager.getInstance(context)

        val configuration = UpdateConfiguration()
        configuration.setJumpInstallPage(true)  //更新后跳转更新页面
        configuration.isShowNotification = true    //显示通知栏
        configuration.isForcedUpgrade = apkUpDateBean.isForced  //是否强制下载
        configuration.isShowBgdToast = true //更新toast

        /**
         * ApkName需固定写死  因为是根据名称来删除旧的安装包的 如果新名称和旧名称不同将找不到旧APK
         *  详情: HttpDownloadManager 74行 runnable
         * 由于Android 10的原因  APk放在 /storage/emulated/0/Android/data/packageName /cache
         */

        manager!!.setApkName("${context.getString(R.string.app_name)}.apk")
            .setApkVersionName("${apkUpDateBean.versionName}")
            .setApkUrl("http://wuio.worldunion.cn:9012/App-Survey.apk")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setConfiguration(configuration)
            .setApkVersionCode(apkUpDateBean.versionCode)  //设置了此参数，那么会自动判断是否需要更新弹出提示框
            .setApkDescription(apkUpDateBean.upDateContent)
            .setApkMD5(apkUpDateBean.md5)
            .setApkSize(apkUpDateBean.apkSize)
            .download();
    }


    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_DESTROY -> {
                onDestroy()
            }
            else->{}
        }
    }

    private fun onDestroy() {
        manager?.release()
    }
}